package com.xnyzc.lhy.mis.service.impl.cms.office;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.xnyzc.lhy.common.component.config.GlobalConfig;
import com.xnyzc.lhy.common.entity.Rv;
import com.xnyzc.lhy.common.exception.PangException;
import com.xnyzc.lhy.common.penum.EErrorCode;
import com.xnyzc.lhy.common.util.*;
import com.xnyzc.lhy.mis.entity.area.OaSysArea;
import com.xnyzc.lhy.mis.entity.cms.OaSysRole;
import com.xnyzc.lhy.mis.entity.cms.OaSysRoleOffice;
import com.xnyzc.lhy.mis.entity.dictionaries.OaSysDict;
import com.xnyzc.lhy.mis.entity.param.cms.OfficeParam;
import com.xnyzc.lhy.mis.entity.param.cms.PageDTO;
import com.xnyzc.lhy.mis.entity.param.cms.UpdateOfficeParam;
import com.xnyzc.lhy.mis.entity.result.cms.SysUserResults;
import com.xnyzc.lhy.mis.entity.result.office.ResultOffice;
import com.xnyzc.lhy.mis.entity.sidebar.OaCUserOffice;
import com.xnyzc.lhy.mis.entity.sidebar.OaSysOffice;
import com.xnyzc.lhy.mis.entity.sidebar.OaSysOfficeOrder;
import com.xnyzc.lhy.mis.entity.system.OaSysUser;
import com.xnyzc.lhy.mis.entity.user.OaCUser;
import com.xnyzc.lhy.mis.entity.user.OaDUserOffice;
import com.xnyzc.lhy.mis.mapper.area.OaSysAreaMapper;
import com.xnyzc.lhy.mis.mapper.cms.OaSysRoleMapper;
import com.xnyzc.lhy.mis.mapper.cms.OaSysRoleOfficeMapper;
import com.xnyzc.lhy.mis.mapper.dictionaries.OaSysDictMapper;
import com.xnyzc.lhy.mis.mapper.sidebar.OaCUserOfficeMapper;
import com.xnyzc.lhy.mis.mapper.sidebar.OaSysOfficeMapper;
import com.xnyzc.lhy.mis.mapper.system.OaSysUserMapper;
import com.xnyzc.lhy.mis.mapper.user.OaCUserMapper;
import com.xnyzc.lhy.mis.mapper.user.OaDUserOfficeMapper;
import com.xnyzc.lhy.mis.service.cms.office.OfficeService;
import com.xnyzc.lhy.mis.service.cms.util.IOaSysGetOfficeIdListService;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;

/**
 * <p>
 * 机构相关
 * </p>
 *
 * @author wangshuo
 * @since 2019-08-08
 */
@Service
public class OfficeServiceImpl  implements OfficeService  {

    @Autowired
    private OaSysUserMapper oaSysUserMapper;

    @Autowired
    private OaSysRoleMapper oaSysRoleMapper;

    @Autowired
    private OaSysOfficeMapper oaSysOfficeMapper;

    @Autowired
    private OaSysDictMapper oaSysDictMapper;

    @Autowired
    private OaSysAreaMapper oaSysAreaMapper;

    @Autowired
    private IOaSysGetOfficeIdListService iOaSysGetOfficeIdListService;

    @Autowired
    private OaDUserOfficeMapper oaDUserOfficeMapper;

    @Autowired
    private OaCUserOfficeMapper oaCUserOfficeMapper;

    @Autowired
    private OaSysRoleOfficeMapper oaSysRoleOfficeMapper;

    @Autowired
    private OaCUserMapper oaCUserMapper;

    /**
     * 根据条件分页查询供应商列表
     * @param cityName
     * @param officeName
     * @return
     */
    @Override
    public Rv getOfficesByConditions(String cityName,String officeName,Integer currentPage,Integer pageSize) {
        long userId = TokenUtil.getTokenUserId();
        String tag = TokenUtil.getTag();
        if(CheckUtil.objIsEmpty(userId,tag)){
            throw PangException.create(EErrorCode.missingArg);
        }
        QueryWrapper<OaSysOffice> wrapper = new QueryWrapper<>();
        wrapper.ne(OaSysOffice.PARENT_ID,1);
        if(CheckUtil.strIsNotEmpty(cityName)){
            wrapper.eq(OaSysOffice.ADDRESS,cityName);
        }
        if(CheckUtil.strIsNotEmpty(officeName)){
            wrapper.like(OaSysOffice.NAME,officeName);
        }
        IPage<OaSysOffice> page = new Page<>();
        page.setCurrent(currentPage);
        page.setSize(pageSize);
        IPage<OaSysOffice> result = oaSysOfficeMapper.selectPage(page, wrapper);
        return Rv.wrap(result);
    }

    /**
     * 获取机构数据
     *
     * @return
     */
    @Override
    public Rv getOfficeFindList(OfficeParam officeParam) {
        Long sysUserId = TokenUtil.getTokenUserId();
        String tag = TokenUtil.getTag();
        List<Long> selectOfficeIdList = iOaSysGetOfficeIdListService.selectOfficeIdList(sysUserId);
        List<Map<String, Object>> mapList = new ArrayList<>();
        // 查询机构
        QueryWrapper<OaSysOffice> cUserQueryWrapper = new QueryWrapper<>();
        cUserQueryWrapper.in(OaSysOffice.OFFICE_ID, selectOfficeIdList).eq(OaSysOffice.TAG, tag).orderByAsc(OaSysOffice.TYPE);
        List<OaSysOffice> officeList = oaSysOfficeMapper.selectList(cUserQueryWrapper);
        for (int i = 0; i < officeList.size(); i++) {
            OaSysOffice e = officeList.get(i);
            Map<String, Object> map = Maps.newHashMap();
            map.put("name", e.getName());
            map.put("id", e.getOfficeId());
            map.put("pId", e.getParentId());
            mapList.add(map);
        }
        JSONArray resultList = ListToTreeUtil.listToTree(JSONArray.parseArray(JSON.toJSONString(mapList)), "id", "pId", "children");
        return Rv.wrap(EErrorCode.success, resultList);
    }

    /**
     * 获取当前用户有权限访问的部门
     *
     * @return
     */
    public List<OaSysOffice> getOfficeList(Long userId) {
        List<OaSysOffice> officeList = null;
        if (userId == 1L) {
            officeList = oaSysOfficeMapper.findAllList(new OaSysOffice());
        } else {
            OaSysUser user = oaSysUserMapper.selectById(userId);
            GlobalConfig config = new GlobalConfig();
            config.getSqlMap().put("dsf", dataScopeFilter(user, "a", ""));
            config.setOfficeId(user.getOfficeId());
            officeList = oaSysOfficeMapper.findList(config);
        }
        return officeList;
    }

    /**
     * 数据范围过滤
     *
     * @param user        当前用户对象
     * @param officeAlias 机构表别名，多个用“,”逗号隔开。
     * @param userAlias   用户表别名，多个用“,”逗号隔开，传递空，忽略此参数
     * @return 标准连接条件对象
     */
    public String dataScopeFilter(OaSysUser user, String officeAlias, String userAlias) {
        StringBuilder sqlString = new StringBuilder();
        // 进行权限过滤，多个角色权限范围之间为或者关系。
        List<String> dataScope = Lists.newArrayList();
        List<OaSysRole> sysRoleList = getSysRole();
        //查询公司
        OaSysOffice companyOffice = getOffice(Long.valueOf(user.getCompanyId()));
        //查询部门
        OaSysOffice office = getOffice(Long.valueOf(user.getOfficeId()));
        // 超级管理员，跳过权限过滤
        if (user.getSysUserId() != 1L) {
            boolean isDataScopeAll = false;
            for (OaSysRole r : sysRoleList) {
                for (String oa : StringUtils.split(officeAlias, ",")) {
                    if (!dataScope.contains(r.getDataScope()) && StringUtils.isNotBlank(oa)) {
                        if (GlobalConfig.DATA_SCOPE_ALL.equals(r.getDataScope())) {
                            isDataScopeAll = true;
                        } else if (GlobalConfig.DATA_SCOPE_COMPANY_AND_CHILD.equals(r.getDataScope())) {
                            sqlString.append(" OR " + oa + ".office_id = '" + user.getCompanyId() + "'");
                            sqlString.append(" OR " + oa + ".parent_ids LIKE '" + companyOffice.getParentIds() + user.getCompanyId() + ",%'");
                        } else if (GlobalConfig.DATA_SCOPE_COMPANY.equals(r.getDataScope())) {
                            sqlString.append(" OR " + oa + ".office_id = '" + user.getCompanyId() + "'");
                            // 包括本公司下的部门 （type=1:公司；type=2：部门）
                            sqlString.append(" OR (" + oa + ".parent_id = '" + user.getCompanyId() + "' AND " + oa + ".type = '2')");
                        } else if (GlobalConfig.DATA_SCOPE_OFFICE_AND_CHILD.equals(r.getDataScope())) {
                            sqlString.append(" OR " + oa + ".office_id = '" + user.getOfficeId() + "'");
                            sqlString.append(" OR " + oa + ".parent_ids LIKE '" + office.getParentIds() + user.getOfficeId() + ",%'");
                        } else if (GlobalConfig.DATA_SCOPE_OFFICE.equals(r.getDataScope())) {
                            sqlString.append(" OR " + oa + ".office_id = '" + user.getOfficeId() + "'");
                        } else if (GlobalConfig.DATA_SCOPE_CUSTOM.equals(r.getDataScope())) {
                            sqlString.append(" OR EXISTS (SELECT 1 FROM oa_sys_role_office WHERE role_id = '" + r.getRoleId() + "'");
                            sqlString.append(" AND office_id = " + oa + ".office_id)");
                        }
                        dataScope.add(r.getDataScope());
                    }
                }
            }
            // 如果没有全部数据权限，并设置了用户别名，则当前权限为本人；如果未设置别名，当前无权限为已植入权限
            if (!isDataScopeAll) {
                if (StringUtils.isNotBlank(userAlias)) {
                    for (String ua : StringUtils.split(userAlias, ",")) {
                        sqlString.append(" OR " + ua + ".office_id = '" + user.getSysUserId() + "'");
                    }
                } else {
                    for (String oa : StringUtils.split(officeAlias, ",")) {
                        sqlString.append(" OR " + oa + ".office_id IS NULL");
                    }
                }
            } else {
                // 如果包含全部权限，则去掉之前添加的所有条件，并跳出循环。
                sqlString = new StringBuilder();
            }
        }
        if (StringUtils.isNotBlank(sqlString.toString())) {
            return " AND (" + sqlString.substring(4) + ")";
        }
        return "";
    }

    /**
     * 查询权限表
     *
     * @return
     */
    private List<OaSysRole> getSysRole() {
        QueryWrapper<OaSysRole> queryWrapper = new QueryWrapper<>();
        List<OaSysRole> oaSysRoleList = oaSysRoleMapper.selectList(queryWrapper);
        return oaSysRoleList;
    }

    /**
     * 查询公司或部门
     *
     * @return
     */
    private OaSysOffice getOffice(Long office) {
        QueryWrapper<OaSysOffice> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(OaSysOffice.OFFICE_ID, office);
        OaSysOffice oaSysRole = oaSysOfficeMapper.selectOne(queryWrapper);
        return oaSysRole;
    }

    /**
     * 获取点击机构列表
     *
     * @return
     */
    @Override
    public Rv getClickOfficeList(OfficeParam officeParam) {
        String parentId = officeParam.getParentId();
        Long sysUserId = TokenUtil.getTokenUserId();
        List<Long> selectOfficeIdList = iOaSysGetOfficeIdListService.selectOfficeIdList(sysUserId);
        String tag = TokenUtil.getTag();
        QueryWrapper<OaSysOffice> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc(OaSysOffice.CREATE_TIME);
        if (CheckUtil.strIsEmpty(parentId)) {
            queryWrapper.like(OaSysOffice.PARENT_IDS, parentId).eq(OaSysOffice.TAG, tag).in(OaSysOffice.OFFICE_ID, selectOfficeIdList);
        } else {
            queryWrapper.eq(OaSysOffice.PARENT_ID, parentId).eq(OaSysOffice.TAG, tag);
        }
        List<OaSysOffice> oaSysOfficeList = oaSysOfficeMapper.selectList(queryWrapper);
        List<String> areaIdList = new ArrayList<>();
        for (OaSysOffice office : oaSysOfficeList) {
            areaIdList.add(office.getAreaId());
        }
        QueryWrapper<OaSysArea> areaQueryWrapper = new QueryWrapper<>();
        areaQueryWrapper.in(OaSysArea.AREA_ID, areaIdList);
        List<OaSysArea> oaSysAreaList = oaSysAreaMapper.selectList(areaQueryWrapper);
        List<Map<String, Object>> menuMapList = ListToTreeUtil.getOfficeList(oaSysOfficeList, oaSysAreaList, "");
        JSONArray resultList = ListToTreeUtil.listToTree(JSONArray.parseArray(JSON.toJSONString(menuMapList)), "value", "pId", "children");
        return Rv.wrap(EErrorCode.success, resultList);
    }

    /**
     * 讲查询结果放进出参实体列表中
     *
     * @param detail
     * @return
     */
    private ResultOffice listOfficeDetail(OaSysOffice detail, List<OaSysOffice> officeList) {
        OaSysArea area = getSysAreaList(Long.valueOf(detail.getAreaId()));
        // 查询机构
        List<OaSysDict> dictTypeList = getDictTypeList();
        // 查询等级
        List<OaSysDict> dictGradeList = getDictGradeList();
        ResultOffice result = new ResultOffice();
        result.setAreaName(area.getName());
        result.setGrade(detail.getGrade());
        result.setOfficeId(detail.getOfficeId());
        result.setParentId(detail.getParentId());
        result.setParentIds(detail.getParentIds());
        result.setName(detail.getName());
        result.setCode(detail.getCode());
        result.setType(String.valueOf(detail.getType()));
        result.setAddress(detail.getAddress());
        result.setMaster(detail.getMaster());
        result.setPhone(detail.getPhone());
        result.setEmail(detail.getEmail());
        result.setUseable(detail.getUseable());
        result.setPrimaryPerson(detail.getPrimaryPerson());
        result.setDeputyPerson(detail.getDeputyPerson());
        result.setPrimaryPersonName("");
        result.setDeputyPersonName("");
        OaCUser primary = oaCUserMapper.selectById(detail.getPrimaryPerson());
        OaCUser deputy = oaCUserMapper.selectById(detail.getDeputyPerson());
        if (CheckUtil.objIsNotEmpty(primary)) {
            result.setPrimaryPersonName(primary.getUserName());
        }
        if (CheckUtil.objIsNotEmpty(deputy)) {
            result.setDeputyPersonName(deputy.getUserName());
        }
        if (EmptyUtil.isNotEmpty(dictTypeList)) {
            for (OaSysDict dict : dictTypeList) {
                if (Long.valueOf(detail.getType()).equals(dict.getDictId())) {
                    result.setType(dict.getLabel());
                }
            }
        }
        if (EmptyUtil.isNotEmpty(dictGradeList)) {
            for (OaSysDict dict : dictGradeList) {
                if (Long.valueOf(detail.getType()).equals(dict.getDictId())) {
                    result.setGrade(dict.getLabel());
                }
            }
        }
        OaSysOffice sysOffice = oaSysOfficeMapper.selectById(detail.getParentId());
        if (CheckUtil.objIsNotEmpty(sysOffice)) {
            result.setParentName(sysOffice.getName());
        } else {
            OaSysOffice office = oaSysOfficeMapper.selectById(officeList.get(0).getOfficeId());
            result.setParentName(office.getName());
        }
        result.setSort(detail.getSort());
        result.setAreaId(detail.getAreaId());
        result.setParentAreaId(area.getParentId());
        result.setCreateTime(DateFormatUtils.format(detail.getCreateTime(), "yyyy-MM-dd HH:mm:ss"));
        return result;
    }

    /**
     * 查询机构类型
     *
     * @return
     */
    private List<OaSysDict> getDictTypeList() {
        QueryWrapper<OaSysDict> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(OaSysDict.TYPE, "sys_office_type");
        List<OaSysDict> dictTypeList = oaSysDictMapper.selectList(queryWrapper);
        return dictTypeList;
    }

    /**
     * 查询城市
     *
     * @return
     */
    private OaSysArea getSysAreaList(Long areaId) {
        QueryWrapper<OaSysArea> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(OaSysArea.AREA_ID, areaId);
        OaSysArea area = oaSysAreaMapper.selectOne(queryWrapper);
        return area;
    }

    /**
     * 查询机构等级
     *
     * @return
     */
    private List<OaSysDict> getDictGradeList() {
        QueryWrapper<OaSysDict> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(OaSysDict.TYPE, "sys_office_grade");
        List<OaSysDict> dictGradeList = oaSysDictMapper.selectList(queryWrapper);
        return dictGradeList;
    }

    /**
     * 获取机构详情
     *
     * @return
     */
    @Override
    public Rv getOfficeDetail(OfficeParam officeParam) {
        String tag = TokenUtil.getTag();
        Map<String, Object> map = new HashMap<>(16);
        List<ResultOffice> resultList = new ArrayList<>();
        // 获取机构树
        List<Long> officeIdList = iOaSysGetOfficeIdListService.selectOfficeIdList(TokenUtil.getTokenUserId());
        QueryWrapper<OaSysOffice> officeQueryWrapper = new QueryWrapper<>();
        officeQueryWrapper.eq(OaSysOffice.TYPE, 1);
        officeQueryWrapper.in(OaSysOffice.OFFICE_ID, officeIdList);
        officeQueryWrapper.eq(OaSysOffice.TAG, tag);
        List<OaSysOffice> officeList = oaSysOfficeMapper.selectList(officeQueryWrapper);
        List<Map<String, Object>> officeMapList = new ArrayList<>();
        if (CheckUtil.objIsNotEmpty(officeParam.getOfficeId())) {
            // 查询机构
            OaSysOffice detail = getOffice(officeParam.getOfficeId());
            if (CheckUtil.objIsEmpty(detail)) {
                throw PangException.create(EErrorCode.missingArg);
            }
            // 处理结果
            ResultOffice result = listOfficeDetail(detail, officeList);
            resultList.add(result);
            officeMapList = ListToTreeUtil.getOfficeList(officeList, new ArrayList<>(), String.valueOf(officeParam.getOfficeId()));
        } else {
            resultList.add(new ResultOffice());
            officeMapList = ListToTreeUtil.getOfficeList(officeList, new ArrayList<>(), "");
        }
        map.put("result", resultList);
        JSONArray officeResultList = ListToTreeUtil.listToTree(JSONArray.parseArray(JSON.toJSONString(officeMapList)), "id", "pId", "children");
        map.put("officeList", officeResultList);
        // 查询区域
        QueryWrapper<OaSysArea> queryWrapper = new QueryWrapper<>();
        queryWrapper.ne(OaSysArea.TYPE, 4);
        List<OaSysArea> areaList = oaSysAreaMapper.selectList(queryWrapper);
        List<Map<String, Object>> areaMapList = ListToTreeUtil.getAreaList(areaList);
        JSONArray areaResultList = ListToTreeUtil.listToTree(JSONArray.parseArray(JSON.toJSONString(areaMapList)), "id", "pId", "children");
        map.put("areaList", areaResultList);
        // 机构等级
        QueryWrapper<OaSysDict> gradeQueryWrapper = new QueryWrapper<>();
        gradeQueryWrapper.eq(OaSysDict.TYPE, "sys_office_grade");
        gradeQueryWrapper.eq(OaSysDict.TAG, tag);
        List<OaSysDict> gradeList = oaSysDictMapper.selectList(gradeQueryWrapper);
        map.put("gradeList", gradeList);
        // 机构类型
        QueryWrapper<OaSysDict> typeQueryWrapper = new QueryWrapper<>();
        typeQueryWrapper.eq(OaSysDict.TYPE, "sys_office_type");
        typeQueryWrapper.eq(OaSysDict.TAG, tag);
        // 目前只留下公司和部门
        typeQueryWrapper.lt(OaSysDict.VALUE, 3);
        List<OaSysDict> typeList = oaSysDictMapper.selectList(typeQueryWrapper);
        map.put("typeList", typeList);
        return Rv.wrap(EErrorCode.success, map);
    }

    /**
     * 机构新增、修改
     *
     * @return
     */
    @Override
    public Rv getUpdateOffice(UpdateOfficeParam param) {
        Long userId = TokenUtil.getTokenUserId();
        String tag = TokenUtil.getTag();
        Date date = new Date();
        String oldParentIds = "";
        String newParentIds = "";
        Long id = 0L;
        // 新增
        if (CheckUtil.objIsEmpty(param.getOfficeId())) {
            OaSysOffice newOffice = oaSysOfficeMapper.selectById(param.getParentId());
            id = IDUtil.nextId();
            newParentIds = newOffice.getParentIds();
            oldParentIds = newOffice.getParentIds();
            OaSysOffice office = new OaSysOffice();
            if (CheckUtil.objIsEmpty(param.getType())) {
                throw PangException.create(EErrorCode.mainType);
            }
            office.setType(param.getType());
            office.setParentId(String.valueOf(newOffice.getOfficeId()));
            office.setParentIds(newOffice.getParentIds() + newOffice.getOfficeId() + ",");
            office.setOfficeId(id);
            office.setTag(tag);
            office.setCreateTime(date);
            office.setCreateUser(userId);
            office.setUpdateUser(userId);
            office.setUpdateTime(date);
            office.setAddress(param.getAddress());
            office.setAreaId(param.getAreaId());
            office.setMaster(param.getMaster());
//            office.setDeputyPerson(param.getDeputyPersonId());
            office.setDeputyPerson(param.getDeputyPerson());
            office.setEmail(param.getEmail());
            office.setSort(new BigDecimal(param.getSort()));
            office.setGrade(String.valueOf(param.getGrade()));
            office.setUseable(param.getUseable());
//            office.setPrimaryPerson(param.getPrimaryPersonId());
            office.setPrimaryPerson(param.getPrimaryPerson());
            office.setName(param.getName());
            office.setPhone(param.getPhone());
            QueryWrapper<OaSysOffice> queryWrapper = new QueryWrapper<>();
            queryWrapper.orderByDesc(OaSysOffice.CODE);
            List<OaSysOffice> officeList = oaSysOfficeMapper.selectList(queryWrapper);
            Integer codeNum = Integer.valueOf(officeList.get(0).getCode()) + 1;
            office.setCode(String.valueOf(codeNum));
            oaSysOfficeMapper.insert(office);
            OaSysRoleOffice role = new OaSysRoleOffice();
            role.setOfficeId(id);
            role.setRoleId(3L);
            role.setLinkedId(IDUtil.nextId());
            role.setCreateTime(date);
            role.setTag(tag);
            role.setUpdateTime(date);
            role.setCreateUser(userId);
            role.setUpdateUser(userId);
            oaSysRoleOfficeMapper.insert(role);
        }
        // 修改
        else {
            // 需修改的实体
            OaSysOffice office = oaSysOfficeMapper.selectById(param.getOfficeId());
            id = param.getOfficeId();
            oldParentIds = office.getParentIds();
            // 选择的实体
            OaSysOffice newOffice = oaSysOfficeMapper.selectById(param.getParentId());
            if (newOffice != null && !String.valueOf(id).equals(param.getParentId())) {
                office.setParentId(String.valueOf(newOffice.getOfficeId()));
                office.setParentIds(newOffice.getParentIds() + newOffice.getOfficeId() + ",");
            }
            newParentIds = office.getParentIds();
            office.setTag(tag);
            office.setUpdateUser(userId);
            office.setUpdateTime(date);
            office.setAddress(param.getAddress());
            office.setAreaId(param.getAreaId());
            office.setMaster(param.getMaster());
//            office.setDeputyPerson(param.getDeputyPersonId());
            office.setDeputyPerson(param.getDeputyPerson());
            office.setSort(new BigDecimal(param.getSort()));
            office.setEmail(param.getEmail());
            office.setGrade(String.valueOf(param.getGrade()));
            office.setType(param.getType());
            office.setUseable(param.getUseable());
//            office.setPrimaryPerson(param.getPrimaryPersonId());
            office.setPrimaryPerson(param.getPrimaryPerson());
            office.setName(param.getName());
            office.setPhone(param.getPhone());
            oaSysOfficeMapper.updateById(office);
        }
        if (!String.valueOf(id).equals(param.getParentId())) {
            // 更新子节点 parentIds
            QueryWrapper<OaSysOffice> queryWrapper = new QueryWrapper<>();
            queryWrapper.like(OaSysOffice.PARENT_IDS, id);
            List<OaSysOffice> likeOffice = oaSysOfficeMapper.selectList(queryWrapper);
            for (OaSysOffice l : likeOffice) {
                l.setUpdateUser(userId);
                l.setUpdateTime(date);
                l.setParentIds(l.getParentIds().replace(oldParentIds, newParentIds));
                oaSysOfficeMapper.updateById(l);
            }
        }
        param.setOfficeId(id);

        return Rv.wrap(EErrorCode.updateSuccess);
    }

    /**
     * 机构删除
     *
     * @return
     */
    @Override
    public Rv getDeleteOffice(OfficeParam officeParam) {
        Long userId = TokenUtil.getTokenUserId();
        String tag = TokenUtil.getTag();
        List<String> roleList = TokenUtil.getRoleDataScope();
        if (!roleList.contains(GlobalConfig.DATA_SCOPE_ALL)) {
            throw PangException.create(EErrorCode.authErr);
        }
        if (CheckUtil.objIsEmpty(officeParam.getOfficeId())) {
            throw PangException.create(EErrorCode.missingArg);
        }
        QueryWrapper<OaCUserOffice> cUserQueryWrapper = new QueryWrapper<>();
        cUserQueryWrapper.eq(OaCUserOffice.OFFICE_ID, officeParam.getOfficeId());
        cUserQueryWrapper.eq(OaCUserOffice.TAG, tag);
        List<OaCUserOffice> cUserOfficeList = oaCUserOfficeMapper.selectList(cUserQueryWrapper);
        QueryWrapper<OaDUserOffice> dUserQueryWrapper = new QueryWrapper<>();
        dUserQueryWrapper.eq(OaCUserOffice.OFFICE_ID, officeParam.getOfficeId());
        dUserQueryWrapper.eq(OaCUserOffice.TAG, tag);
        List<OaDUserOffice> dUserOfficeList = oaDUserOfficeMapper.selectList(dUserQueryWrapper);
        if (!cUserOfficeList.isEmpty() || !dUserOfficeList.isEmpty()) {
            throw PangException.create(EErrorCode.unableDelete);
        }
        QueryWrapper<OaSysOffice> officeQueryWrapper = new QueryWrapper<>();
        officeQueryWrapper.eq(OaSysOffice.TAG, tag);
        officeQueryWrapper.eq(OaSysOffice.OFFICE_ID, officeParam.getOfficeId()).or().like(OaSysOffice.PARENT_IDS, officeParam.getOfficeId());
        oaSysOfficeMapper.delete(officeQueryWrapper);
        return Rv.wrap(EErrorCode.deleteSuccess);
    }

    /**
     * 机构负责人列表
     *
     * @return
     */
    @Override
    public Rv getOfficeUserList(OfficeParam officeParam) {
        String tag = TokenUtil.getTag();
        List<SysUserResults> resultsList = new ArrayList<>();
        if (CheckUtil.objIsEmpty(officeParam.getOfficeId())) {
            return Rv.wrap(EErrorCode.success, resultsList);
        }
        QueryWrapper<OaCUserOffice> officeQueryWrapper = new QueryWrapper<>();
        officeQueryWrapper.eq(OaCUserOffice.TAG, tag);
        officeQueryWrapper.in(OaCUserOffice.OFFICE_ID, officeParam.getOfficeId());
        List<OaCUserOffice> officeList = oaCUserOfficeMapper.selectList(officeQueryWrapper);
        if (officeList.isEmpty()) {
            return Rv.wrap(EErrorCode.success, resultsList);
        }
        List<Long> userList = new ArrayList<>();
        for (OaCUserOffice office : officeList) {
            userList.add(office.getUserId());
        }
        // 模糊查询管理员姓名
        String query = officeParam.getQuery();
        QueryWrapper<OaCUser> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotEmpty(query)) {
            queryWrapper.like(OaCUser.USER_NAME, query);
        }
        queryWrapper.eq(OaCUser.TAG, tag);
        queryWrapper.in(OaCUser.USER_ID, userList);
        List<OaCUser> cUserList = oaCUserMapper.selectList(queryWrapper);
        SysUserResults results = new SysUserResults();
        for (OaCUser user : cUserList) {
            results = new SysUserResults();
            results.setSysUserId(user.getUserId());
            results.setName(user.getUserName());
            results.setMobile(user.getUserPhone());
            resultsList.add(results);
        }
        return Rv.wrap(EErrorCode.success, resultsList);
    }

    /**
     * 获取只限于公司数据
     *
     * @return
     */
    @Override
    public Rv getOfficeCompanyList(OfficeParam officeParam) {
        Long sysUserId = TokenUtil.getTokenUserId();
        String tag = TokenUtil.getTag();
        List<Long> selectOfficeIdList = iOaSysGetOfficeIdListService.selectOfficeIdList(sysUserId);
        List<Map<String, Object>> mapList = new ArrayList<>();
        // 查询机构
        QueryWrapper<OaSysOffice> cUserQueryWrapper = new QueryWrapper<>();
        cUserQueryWrapper.in(OaSysOffice.OFFICE_ID, selectOfficeIdList).eq(OaSysOffice.TAG, tag).eq(OaSysOffice.TYPE, 1);
        List<OaSysOffice> officeList = oaSysOfficeMapper.selectList(cUserQueryWrapper);
        for (int i = 0; i < officeList.size(); i++) {
            OaSysOffice e = officeList.get(i);
            Map<String, Object> map = Maps.newHashMap();
            map.put("pId", e.getParentId());
            map.put("code", e.getCode());
            map.put("id", e.getOfficeId());
            map.put("name", e.getName());
            mapList.add(map);
        }
        JSONArray resultList = ListToTreeUtil.listToTree(JSONArray.parseArray(JSON.toJSONString(mapList)), "id", "pId", "children");
        return Rv.wrap(EErrorCode.success, resultList);
    }

    /**
     * 获取运力供应商列表
     *
     * @param officeParam
     */
    @Override
    public Rv getOfficeList(UpdateOfficeParam officeParam) {
        List<OaSysOffice> companyByAdCode = oaSysOfficeMapper.getCompanyByAdCode(officeParam.getAdCode());
        Iterator<OaSysOffice> iterator = companyByAdCode.iterator();
        List<OaSysOffice> officeParamList = new ArrayList<>();
        while (iterator.hasNext()) {
            OaSysOffice param = new OaSysOffice();
            OaSysOffice oaSysOffice = iterator.next();
            param.setOfficeId(oaSysOffice.getOfficeId());
            if (CheckUtil.strIsEmpty(oaSysOffice.getExpand1())){
                param.setDistributionExpress("0");
                param.setDistributionCompact("0");
                param.setDistributionPremium("0");
                param.setDistributionLuxury("0");
                param.setName(oaSysOffice.getName());
                param.setPrimaryPerson(oaSysOffice.getPrimaryPerson());
            }else {
                String ex1=oaSysOffice.getExpand1();
                String[] disAll = ex1.split(",");
                param.setDistributionExpress(disAll[0].split(":")[1]);
                param.setDistributionCompact(disAll[1].split(":")[1]);
                param.setDistributionPremium(disAll[2].split(":")[1]);
                param.setDistributionLuxury(disAll[3].split(":")[1]);
                param.setName(oaSysOffice.getName());
                param.setPrimaryPerson(oaSysOffice.getPrimaryPerson());
            }

            officeParamList.add(param);
        }
        return Rv.wrap(EErrorCode.success,officeParamList);
    }

    /**
     * 更新分单比例数据
     *
     * @param officeParam
     * @return
     */
    @Override
    public Rv updateOffice(List<OfficeParam> officeParam,Long sysUserId) {
        if (CheckUtil.collectionIsEmpty(officeParam)) {
            Rv.wrap(EErrorCode.missingArg);
        }
        Boolean flag = false;
        for (OfficeParam param :
                officeParam) {
            OaSysOffice office = oaSysOfficeMapper.selectById(param.getOfficeId());
            List<OaSysOffice> companyByAdCode = oaSysOfficeMapper.getCompanyByAdId(office.getAreaId());
            if (flag != true && companyByAdCode.size() != officeParam.size()) {
                return Rv.wrap(EErrorCode.noData);
            }
            flag = true;
            String distributionAll = "0:" + checkParam(param.getDistributionExpress()) + "," +
                    "1:" + checkParam(param.getDistributionCompact()) + "," +
                    "2:" + checkParam(param.getDistributionLuxury()) + "," +
                    "3:" + checkParam(param.getDistributionPremium()) + ",";
            office.setExpand1(distributionAll);
            office.setUpdateUser(sysUserId);
            office.setUpdateTime(new Date());
            oaSysOfficeMapper.updateById(office);
        }
        return Rv.wrap(EErrorCode.updateWalletSuccess);
    }


    public String checkParam(String v) {
        if (CheckUtil.strIsEmpty(v)) {
            v = "0";
        }
        return v;
    }

    public static void main(String[] args) {
        String a="0:30,1:30,2:30,3:30,";
        String[] b = a.split(",");
        System.out.println(b.length);
    }


}
